/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Modelos.buscacliente;
import Modelos.MiModelo;
import BD.LeePropiedades;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author Otto
 */
public class devoluciones extends javax.swing.JInternalFrame {

    private final JTextField editorcomp;
    private String archivoRecurso = "controlador-bd";

    /**
     * Creates new form devoluciones
     */
    public devoluciones() {
        initComponents();
        
        editorcomp = (JTextField) clientebusca.getEditor().getEditorComponent();
        final DefaultComboBoxModel value2;
        value2 = new DefaultComboBoxModel();
        clientebusca.setModel(value2);
        editorcomp.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override
            public void keyPressed(java.awt.event.KeyEvent arg0) {
                int key = arg0.getKeyCode();
                //JOptionPane.showMessageDialog(null, key);
                if (key == java.awt.event.KeyEvent.VK_ENTER) {
                    try {
                        DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
                        LeePropiedades.archivoRecurso = archivoRecurso;
                        Connection conexion = (Connection) DriverManager.getConnection(LeePropiedades.leeID("url"), LeePropiedades.leeID("usuario"), LeePropiedades.leeID("password"));
                        // Se crea un Statement, para realizar la consulta
                        Statement s = (Statement) conexion.createStatement();
                        ResultSet rs = s.executeQuery("select idClientes,nombre from clientes where Nombre like '%" + editorcomp.getText() + "%'");

                        clientebusca.removeAllItems();
//value2.addElement(" ");
                        while (rs.next()) {
                            value2.addElement(new buscacliente(rs.getString("Nombre"), rs.getInt("idClientes")));
                            //value2.addElement(ControladorBD.getString("NombreCliente"));
                        }
                        conexion.close();
                        clientebusca.hidePopup();
                        clientebusca.showPopup();

                    } catch (SQLException ex) {
                        //Logger.getLogger(solicitudcliente.class.getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(null, "Error en BD " + ex.toString());
                        System.out.print(ex.getMessage());
                    }
                }
            }
        });

        tablabusquedacliente.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override
            public void keyPressed(java.awt.event.KeyEvent arg0) {
                int key = arg0.getKeyCode();
                if (key == java.awt.event.KeyEvent.VK_ENTER) {
                    int seleccion = JOptionPane.showOptionDialog(
                            null,
                            "Desea devolver un producto",
                            "Selector de opciones",
                            JOptionPane.YES_NO_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            null, // null para icono por defecto.
                            new Object[]{"Si", "Cancelar"}, // null para YES, NO y CANCEL
                            "opcion 1");

                    if (seleccion == 0) {
                        devuelve();

                    } else if (seleccion == 1) {
                        System.out.println("no elimino");
                    }

                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jcMousePanel1 = new jcMousePanel.jcMousePanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablabusquedacliente = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        clientebusca = new org.jdesktop.swingx.JXComboBox();
        confecha = new javax.swing.JCheckBox();
        Fecha1 = new org.freixas.jcalendar.JCalendarCombo();
        Fecha2 = new org.freixas.jcalendar.JCalendarCombo();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        idcli = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setTitle("DEVOLUCION DE PRODUCTOS");
        setToolTipText("");

        jcMousePanel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fondo/índice.jpg"))); // NOI18N
        jcMousePanel1.setModo(4);
        jcMousePanel1.setName(""); // NOI18N
        jcMousePanel1.setOpaque(false);

        tablabusquedacliente.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        tablabusquedacliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tablabusquedacliente.setRowHeight(20);
        jScrollPane1.setViewportView(tablabusquedacliente);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setOpaque(false);

        clientebusca.setEditable(true);
        AutoCompleteDecorator.decorate(clientebusca);
        clientebusca.setEditable(true);
        clientebusca.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        clientebusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clientebuscaActionPerformed(evt);
            }
        });

        confecha.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        confecha.setText("Por Fecha");
        confecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confechaActionPerformed(evt);
            }
        });

        Fecha1.setEnabled(false);
        Fecha1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        Fecha2.setEnabled(false);
        Fecha2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Desde");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Hasta");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Cliente");

        idcli.setVisible(false);
        idcli.setOpaque(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(103, 103, 103)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(confecha)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(idcli, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(clientebusca, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(Fecha1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                            .addComponent(Fecha2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                    .addContainerGap(458, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(idcli, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(confecha))
                .addGap(10, 10, 10)
                .addComponent(clientebusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Fecha1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Fecha2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(45, 45, 45)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Enter Para Hacer la devolucion");

        javax.swing.GroupLayout jcMousePanel1Layout = new javax.swing.GroupLayout(jcMousePanel1);
        jcMousePanel1.setLayout(jcMousePanel1Layout);
        jcMousePanel1Layout.setHorizontalGroup(
            jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jcMousePanel1Layout.setVerticalGroup(
            jcMousePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jcMousePanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jcMousePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jcMousePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clientebuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clientebuscaActionPerformed

        buscacliente();
    }//GEN-LAST:event_clientebuscaActionPerformed
    public void devuelve() {
        try {
            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            LeePropiedades.archivoRecurso = archivoRecurso;
            Connection conexion = (Connection) DriverManager.getConnection(LeePropiedades.leeID("url"), LeePropiedades.leeID("usuario"), LeePropiedades.leeID("password"));
            // Se crea un Statement, para realizar la consulta
            Statement s = (Statement) conexion.createStatement();
            int p = tablabusquedacliente.getSelectedRow(), cantidad = 0;
            String Cant = JOptionPane.showInputDialog(null, "Cantidad de devolucion");
            cantidad = Integer.parseInt(Cant);

            DefaultTableModel temp = (DefaultTableModel) tablabusquedacliente.getModel();

            ResultSet rs = null;
            rs = s.executeQuery("SELECT idProducto, cantidad FROM producto WHERE idproducto='" + temp.getValueAt(p, 2) + "'");

            int cant = 0;
            while (rs.next()) {
                //mensaj=1;

                cant = rs.getInt("cantidad");
            }
            rs = s.executeQuery("SELECT  cantidad FROM lote WHERE idlote='" + temp.getValueAt(p, 1) + "'");
            int cant2 = 0;
            while (rs.next()) {
                //mensaj=1;

                cant2 = rs.getInt("cantidad");
            }
            rs = s.executeQuery("SELECT  cantidad,devolucion FROM detallesalida WHERE iddetallesalida='" + temp.getValueAt(p, 0) + "'");
            int cant1 = 0, cant22 = 0;
            while (rs.next()) {
                //mensaj=1;
                cant22 = rs.getInt("cantidad");
                cant1 = rs.getInt("devolucion");

            }
            if (cantidad <= ((cant22+cant1)-cant1)) {

                //int cant1 = cantidad;
                int SumaP = cant + cantidad;
                int sumaL = cant2 + cantidad;
                int devolucion = cant1 + cantidad;
                String estado1 = "T", fecha = "";
                
                s.executeUpdate("UPDATE producto SET cantidad='" + SumaP + "' WHERE idProducto =" + temp.getValueAt(p, 2));
                s.executeUpdate("UPDATE detallesalida SET devolucion='" + devolucion + "' WHERE iddetallesalida =" + temp.getValueAt(p, 0));
                s.executeUpdate("UPDATE lote SET cantidad='" + sumaL + "', estado='" + estado1 + "' WHERE idlote =" + temp.getValueAt(p, 1));
            } else {
                JOptionPane.showMessageDialog(null, "Error No se puede hacer la devolucion");
            }
            JOptionPane.showMessageDialog(null, "Devolución operada exitosamente");
            for (int h = temp.getRowCount(); h > 0; h--) {
                // JOptionPane.showMessageDialog(null, "elimina "+h);
                temp.removeRow(h - 1);
            }
            conexion.close();

        } catch (SQLException ex) {
            Logger.getLogger(devoluciones.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void confechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confechaActionPerformed
        // TODO add your handling code here:
        if (confecha.isSelected() == true) {
            Fecha1.setEnabled(true);
            Fecha2.setEnabled(true);
        } else {
            Fecha1.setEnabled(false);
            Fecha2.setEnabled(false);
        }
    }//GEN-LAST:event_confechaActionPerformed
    public void buscacliente() {
        int idPr = 0, idcredito = 0;
        int año = Fecha1.getCalendar().get(Calendar.YEAR);
        int dia = Fecha1.getCalendar().get(Calendar.DAY_OF_MONTH);
        int mes = Fecha1.getCalendar().get(Calendar.MONTH) + 1;
        int año1 = Fecha2.getCalendar().get(Calendar.YEAR);
        int dia1 = Fecha2.getCalendar().get(Calendar.DAY_OF_MONTH);
        int mes1 = Fecha2.getCalendar().get(Calendar.MONTH) + 1;

        String fech1, fech2;

        fech1 = "" + año + "-" + mes + "-" + dia;
        fech2 = "" + año1 + "-" + mes1 + "-" + dia1;
        if (clientebusca.getSelectedIndex() >= 0) {
            //if(evt.getModifiers()==16){
            buscacliente cl = (buscacliente) clientebusca.getSelectedItem();
            idPr = cl.getID();
            idcli.setText(idPr + "");
            try {
                DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
                LeePropiedades.archivoRecurso = archivoRecurso;
                Connection conexion = (Connection) DriverManager.getConnection(LeePropiedades.leeID("url"), LeePropiedades.leeID("usuario"), LeePropiedades.leeID("password"));
                // Se crea un Statement, para realizar la consulta
                Statement s = (Statement) conexion.createStatement();
                int suma = 0;

                MiModelo modelo = new MiModelo();
                tablabusquedacliente.setModel(modelo);
                modelo.addColumn("ID");
                modelo.addColumn("idlote");
                modelo.addColumn("idproducto");
                modelo.addColumn("Nombre producto");
                modelo.addColumn("Cantidad");

                modelo.addColumn("devolucion");
                modelo.addColumn("Fecha");

                TableColumn desaparece = tablabusquedacliente.getColumnModel().getColumn(1);
                desaparece.setMaxWidth(0);
                desaparece.setMinWidth(0);
                desaparece.setPreferredWidth(0);
                tablabusquedacliente.doLayout();
                TableColumn desaparece2 = tablabusquedacliente.getColumnModel().getColumn(2);
                desaparece2.setMaxWidth(0);
                desaparece2.setMinWidth(0);
                desaparece2.setPreferredWidth(0);
                tablabusquedacliente.doLayout();
                String sql = "";
                if (confecha.isSelected() == true) {
                    sql = "SELECT producto.nombre, detallesalida.devolucion,detallesalida.cantidad,salida.fecha,producto.idproducto,lote.idlote,detallesalida.iddetallesalida,clientes.nombre FROM producto INNER JOIN lote ON producto.idproducto = lote.producto_idProducto INNER JOIN detallesalida ON lote.idlote = detallesalida.lote_idlote INNER JOIN salida ON detallesalida.salida_idsalida = salida.idsalida INNER JOIN clientes ON salida.clientes_idclientes = clientes.idclientes WHERE salida.fecha BETWEEN '" + fech1 + "' and '" + fech2 + "' and clientes_idclientes='" + idPr + "'";
                } else {
                    sql = "SELECT producto.nombre, detallesalida.devolucion,detallesalida.cantidad,salida.fecha,producto.idproducto,lote.idlote,detallesalida.iddetallesalida,clientes.nombre FROM producto INNER JOIN lote ON producto.idproducto = lote.producto_idProducto INNER JOIN detallesalida ON lote.idlote = detallesalida.lote_idlote INNER JOIN salida ON detallesalida.salida_idsalida = salida.idsalida INNER JOIN clientes ON salida.clientes_idclientes = clientes.idclientes WHERE clientes_idclientes='" + idPr + "'";
                }
                ResultSet rs = s.executeQuery(sql);

                while (rs.next()) {
                    //JOptionPane.showMessageDialog(null, ""+ControladorBD.getString("nombreusuario"));
                    Object[] fila = new Object[7]; // Hay tres columnas en la tabla
                    // Se rellena cada posición del array con una de las columnas de la tabla en base de datos.
                    fila[0] = rs.getInt("iddetallesalida");
                    fila[1] = rs.getInt("idlote");
                    fila[2] = rs.getInt("idproducto");
                    fila[3] = rs.getString("producto.nombre");
                    fila[4] = rs.getString("detallesalida.cantidad");
                    fila[5] = rs.getString("detallesalida.devolucion");
                    fila[6] = rs.getString("salida.fecha");

                    modelo.addRow(fila);
                }
                conexion.close();

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error en BD " + ex.toString());
                System.out.print(ex.getMessage());
                //Logger.getLogger(solicitudcliente.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.freixas.jcalendar.JCalendarCombo Fecha1;
    private org.freixas.jcalendar.JCalendarCombo Fecha2;
    private org.jdesktop.swingx.JXComboBox clientebusca;
    private javax.swing.JCheckBox confecha;
    private javax.swing.JTextField idcli;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private jcMousePanel.jcMousePanel jcMousePanel1;
    private javax.swing.JTable tablabusquedacliente;
    // End of variables declaration//GEN-END:variables
}
